<template>
    <div>
        <el-dialog title="图片列表" :visible="box_visible" @close="closeBox" :close-on-click-modal="false">
            <div>
                <el-button type="primary" @click="handleAddGroup">添加分组</el-button>
                <el-button type="primary" @click="handleUpload">上传图片</el-button>
                <el-button :type="selectedImgs.length > 0 ? 'danger' : 'info'" :disabled="selectedImgs.length < 1"
                    @click="handleDelBatch">
                    批量删除{{ selectedImgs.length }}
                </el-button>
                <el-button :type="selectedImgs.length > 0 ? 'primary' : 'info'" :disabled="selectedImgs.length < 1"
                    @click="handleSelect">
                    确认选择{{ selectedImgs.length }}
                </el-button>
            </div>
            <div>
                <el-tabs v-model="currentGroupId" type="card" @tab-click="changeGroup" :closable="true"
                    @tab-remove="removeGroup">
                    <el-tab-pane label="查看所有" name="0" :closable="false">
                        <ImgList :multiple="multiple" :img_list="imgList" :selectedImgs="selectedImgs"
                            @on-select="onSelectImage" @on-remove="onRemoveFile">
                        </ImgList>
                    </el-tab-pane>
                    <el-tab-pane v-for="item in fileGroupList" :key="item.attachFileGroupId" :label="item.name"
                        :name="item.attachFileGroupId + ''">
                        <ImgList :multiple="multiple" :img_list="imgList" :selectedImgs="selectedImgs"
                            @on-select="onSelectImage" @on-remove="onRemoveFile">
                        </ImgList>
                    </el-tab-pane>
                </el-tabs>
            </div>
            <el-dialog title="添加分组" :visible.sync="groupVisible" :modal="false" @close="canclAddGroup"
                :close-on-click-modal="false">
                <el-form>
                    <el-form-item label="分组名称">
                        <el-input v-model="newGroup.name"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="saveGroup">确定</el-button>
                        <el-button @click="canclAddGroup">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
            <el-dialog title="图片上传" :visible.sync="uploadVisible" :modal="false" @close="canclUpload"
                :close-on-click-modal="false">
                <el-upload ref="mallUpload" action="#" list-type="picture-card" :auto-upload="false"
                    :http-request="httpRequest" :multiple="true" :on-change="onChange" :on-success="onSuccess"
                    :on-error="onError">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                <i class="el-icon-zoom-in"></i>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleDownload(file)">
                                <i class="el-icon-download"></i>
                            </span>
                            <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                                <i class="el-icon-delete"></i>
                            </span>
                        </span>
                    </div>
                </el-upload>
                <div>
                    <el-button type="primary" @click="uploadImg">确认上传</el-button>
                    <el-button @click="canclUpload">取消</el-button>
                </div>
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script>
import ImgList from '@/components/ImgList/index.vue'
import { upload_action, upload_minio } from '@/api/biz/oss'
import { save_file_infos, file_page, save_file_group, file_group_list, file_group_del, file_del_batch } from '@/api/biz/attachFile';
export default {
    //import引入组件才能使用
    components: { ImgList },
    props: {
        // 支持多选
        multiple: {
            type: Boolean,
            default: true
        },
        box_visible: {
            type: Boolean,
            default: false
        },
    },
    data() {
        return {
            page: {
                page: 1,
                size: 10,
                total: 0
            },
            currentGroupId: '0',
            newGroup: {},
            groupVisible: false,
            uploadVisible: false,
            uploadList: [],
            ossList: [],
            attachFileList: [],
            imgList: [],
            fileGroupList: [],
            selectedImgs: []
        };
    },
    // 计算属性
    computed: {},
    // 监听data中的数据变化
    watch: {},
    // 方法集合
    methods: {
        pageChange(page) {
            this.page.page = page
            this.initPage()
        },
        sizeChange(size) {
            this.page.size = size
            this.initPage()
        },
        initPage() {
            file_page(this.page).then(res => {
                this.imgList = res.data.list
                this.page.total = res.data.total
            })
        },
        initFileGroup() {
            file_group_list().then(res => {
                this.fileGroupList = res.data
            })
        },
        handleAddGroup() {
            this.groupVisible = true
        },
        saveGroup() {
            save_file_group(this.newGroup).then(res => {
                this.$message({
                    message: '添加成功',
                    type: 'success'
                })
                this.groupVisible = false
                this.initFileGroup()
            })
        },
        changeGroup(tab, event) {
            this.page.fileGroupId = tab.name
            this.initPage()
        },
        removeGroup(id) {
            if (id == 0) return
            console.log(id)
            this.$confirm('此操作将删除该分组, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                file_group_del(id).then(res => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.initFileGroup()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        canclAddGroup() {
            this.groupVisible = false
            this.newGroup = {}
        },
        httpRequest(event) {
            let oss = this.ossList[0]
            upload_minio(oss.actionUrl, event.file).then(res => {
            })
            let attachFile = {
                fileName: event.file.name,
                filePath: oss.dir + oss.fileName,
                fileType: event.file.type,
                fileSize: event.file.size,
                attachFileGroupId: this.currentGroupId
            }
            this.attachFileList.push(attachFile)
            this.ossList.splice(0, 1)
            event.onSuccess()
        },
        onChange(file, fileList) {
            if (file.status == "ready") {
                this.uploadList.push(file)
            }
        },
        onSuccess(response, file, fileList) {
            console.log("成功", response, file, fileList)
        },
        onError(err, file, fileList) {
            console.log("失败", err, file, fileList)
        },
        handleUpload() {
            this.uploadVisible = true
        },
        async uploadImg() {
            await upload_action(this.uploadList.length).then(res => {
                this.ossList = res.data
            })
            await this.$refs.mallUpload.submit()
            save_file_infos(this.attachFileList).then(res => {
                this.$message({
                    message: '上传成功',
                    type: 'success'
                })
                this.initPage()
                this.uploadVisible = false
            })
            this.uploadList = []
            this.attachFileList = []
            this.$refs.mallUpload.clearFiles()
        },
        canclUpload() {
            this.uploadList = []
            this.attachFileList = []
            this.$refs.mallUpload.clearFiles()
            this.uploadVisible = false
        },
        onSelectImage(image) {
            if (this.multiple) {
                if (this.selectedImgs.includes(image)) {
                    this.selectedImgs.splice(this.selectedImgs.indexOf(image), 1)
                } else {
                    this.selectedImgs.push(image)
                }
            } else {
                if (this.selectedImgs.includes(image)) {
                    this.selectedImgs = []
                } else {
                    this.selectedImgs = [image]
                }
            }
        },
        handleSelect() {
            this.$emit('on-select', this.selectedImgs)
        },
        handleDelBatch() {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let ids = this.selectedImgs.map(item => item.fileId)
                file_del_batch(ids).then(res => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.selectedImgs = []
                    this.initPage()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        onRemoveFile(id) {
            this.initPage()
        },
        closeBox() {
            this.$emit("on-close")
        }
    },
    // 生命周期，创建完成时（可以访问当前this实例）
    created() {
        this.initPage()
        this.initFileGroup()
    },
    // 生命周期：挂载完成时（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { },//生命周期：创建之前
    beforeMount() { },//生命周期：挂载之前
    beforeUpdate() { },//生命周期：更新之前
    updated() { },//生命周期：更新之后
    beforeDestroy() { },//生命周期：销毁之前
    destroyed() { },//生命周期：销毁完成
    activated() { },//如果页面有keep-alive缓存功能，这个函数会触发执行
}
</script>
<style scoped></style>